package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 左侧菜单栏分类管理
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
   @Autowired
    private CategoryService categoryService;


    /**
     * 新增分类
     * @param category
     * @return
     */
   @PostMapping
   public R<String> save(@RequestBody Category category){
       log.info("category={}",category);
       categoryService.save(category);
     return R.success("新增分类成功!");
   }


   @GetMapping("/page")
   public R<Page> page(int page,int pageSize,String name){
       Page<Category> pageInfo = new Page<>(page,pageSize);
       //条件构造器
       LambdaQueryWrapper<Category> quertWrapper = new LambdaQueryWrapper<>();
       //根据排序来展示
       quertWrapper.orderByAsc(Category::getSort);
       categoryService.page(pageInfo, quertWrapper);
       return R.success(pageInfo);
   }

    /**
     * 根据id删除类别
     * @param id
     * @return
     */
   @DeleteMapping
   public R<String> delete(Long id){
       log.info("删除的类别id为：{}",id);
       //这个方法调用的就是categoryServiceImpl里的remove方法,因为需要加上判断无法直接用mybatisPlus的语句，所以判断业务需要在CategpryServiceImpl判断
       categoryService.remove(id);
       return R.success("分类信息删除成功！");
   }


   @PutMapping
    public R<String> update(@RequestBody Category category){
       log.info("修改的分类信息是:{}",category);
       categoryService.updateById(category);
       return R.success("修改分类信息成功!");
   }

    /**
     * 菜品管理里的菜品分类查询
     * 套餐管理的新增菜品
     */
   @GetMapping("list")
    public R<List<Category>> list(Category category){
       LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
       //先判空，类型不能为空 1为菜品管理 2为套餐管理
       queryWrapper.eq(category.getType() != null,Category::getType,category.getType());
       queryWrapper.orderByDesc(Category::getSort).orderByDesc(Category::getUpdateTime);
       List<Category> list = categoryService.list(queryWrapper);
       return R.success(list);
   }
}
